package com.itlong.cloud.controller.sdkV1.cloud.intercom.server;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.sdk.*;
import com.itlong.cloud.POJO.PO.AppVisitorPassCodeRecordPO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppGetQrcodeVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.PropertyPublicRoleEnum;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudTalkErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudTalkSDKServiceClient;
import com.itlong.cloud.project.app.IAppRoomServiceClient;
import com.itlong.cloud.project.sdk.ICloudTalkSDKServerProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppMineServiceClient;
import com.itlong.cloud.user.app.IAppRegisterServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKServerUserServiceClient;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 * 云对讲SDK服务端用户信息Controller
 * </desc>
 *
 * @createDate 2018/05/11
 */
@RestController
@RequestMapping("/cloud/intercom")
public class CloudTalkSDKServerUserController {


    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkSDKServerUserController.class);

    @Value("${" + PlatformConstants.CLOUDTALK_SDK_USER_TOKEN_KEY + "}")
    private String CLOUDTALK_SDK_USER_TOKEN_KEY;

    @Autowired
    ICloudTalkSDKServerUserServiceClient iCloudTalkSDKServerUserServiceClient;

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;

    @Autowired
    private ICloudTalkSDKServerProjectServiceClient iCloudTalkSDKServerProjectServiceClient;

    @Autowired
    private IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    private IAppMineServiceClient iAppMineServiceClient;

    @Autowired
    IAppRegisterServiceClient iAppRegisterServiceClient;

    @Autowired
    IAppRoomServiceClient iAppRoomServiceClient;

    @Autowired
    ICloudTalkSDKServiceClient iCloudTalkSDKServiceClient;


    /**
     * <desc>
     * 开发者账号申请
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author JuGuang.S
     * @createDate 2018/05/11
     */
    @ResponseBody
    @PostMapping("/server/applicationAccount")
    public Object addHouser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerApplicationAccountDTO accountDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerApplicationAccountDTO.class, request);
            String userName = accountDTO.getUserName();
            String pubKey = accountDTO.getPubKey();
            String projectId = accountDTO.getProjectId();
            String appsecret = accountDTO.getAppsecret();

            //LOG.info("====云对讲SDK开发者账号申请入参:userName：" + userName + " projectId:" + projectId + " pubKey:" + pubKey + " appsecret:" + appsecret);

            String desProjectId = null;
            if (StringUtils.isNotEmpty(projectId)) {
                desProjectId = DesEncryptUtil.projectIdDesEncrypt(projectId) == null ? projectId : DesEncryptUtil.projectIdDesEncrypt(projectId);
            }
            if (desProjectId == null || StringUtils.isEmpty(userName) || StringUtils.isEmpty(pubKey)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if(StringUtils.isEmpty(appsecret)){
                //账号名(合法性及存在性)
                if (iOperatePropertyAccountServiceClient.checkPropertyAccountExist(userName) > 0){
                    return new MessageVO(CloudTalkErrorCodeEnum.SERVER_ACCOUNT_USER_NAME_EXIST_ERR.getErrorCode());
                }
            }
            //检测某项目某角色用户是否已存在（每个项目的每个公共角色，只能有一个用户）
            if (iOperatePropertyAccountServiceClient.checkProjectRoleExist(desProjectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId(), null) > 0) {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),
                        String.format("项目【%s】角色【%s】已存在用户", desProjectId,
                                PropertyPublicRoleEnum.getRoleNameByRoleId(PropertyPublicRoleEnum.DEVELOPER.getRoleId())));
            }

            //根据项目ID和pubKey查询单个项目 判断该项目是否存在，项目状态是否被禁用
            ProjectPO projectPO = iCloudTalkSDKServerProjectServiceClient.getByProjectIdAndPubKey(desProjectId,pubKey);
            if (projectPO == null) {
                return new MessageVO(CloudTalkErrorCodeEnum.PROJECT_NOT_EXIST.getErrorCode());
            }
            if (projectPO.getStatus() == 2) {
                return new MessageVO(CloudTalkErrorCodeEnum.PROJECT_IS_BANNED.getErrorCode());
            }
            //appsecret非空则一个开发者账号可以绑定多个小区
            PropertyUserInfoPO infoPO = null;
            if (StringUtils.isEmpty(appsecret)) {
                infoPO = iCloudTalkSDKServerUserServiceClient.applicationAccount(userName, desProjectId);
            }else{
                infoPO = iCloudTalkSDKServerUserServiceClient.getPropertyUserByAppsecret(appsecret,desProjectId);
            }
            JSONObject js = new JSONObject();
            if(infoPO != null){
                js.put("appId",infoPO.getUserId());
                js.put("appsecret",infoPO.getAppsecret());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端_SDKCloudIntercomServerUserController_applicationAccount】申请开发者账号异常", e);
        }
    }

    /**
     * <desc>
     *    服务端SDK认证
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author JuGuang.S
     * @createDate 2018-05-11
     */
 /*   @ResponseBody
    @PostMapping(path = "/server/sdk/authentication")
    public Object authentication(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerAuthenticationDTO authenticationDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerAuthenticationDTO.class, request);
            String appId = authenticationDTO.getAppId();
            String appsecret = authenticationDTO.getAppsecret();

            if(StringUtils.isEmpty(appId) || StringUtils.isEmpty(appsecret)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //登陆校验及缓存更新
            Integer count = iCloudTalkSDKServerUserServiceClient.sdkServerLogin(appId, appsecret);
            /*if (userCacheVO == null) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_DEVELOP_ERR.getErrorCode());
            }
            JSONObject js = new JSONObject();
            js.put("token", userCacheVO.getToken());
            js.put("expiresIn", RedisConstant.REDIS_CLOUDTALK_SDK_APP_USER_CACHE_TIME);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),count);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK服务端SDK认证_SDKCloudIntercomServerUserController_authentication】服务端SDK认证异常", e);
        }
    }*/

    /**
     * <desc>
     *      设置业主二维码
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/20
     */
    @ResponseBody
    @PostMapping(path = "/server/setOwnerQrCode")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SET_OWNER_QR_CODE_LOG_DESC)
    public Object setOwnerQrCode(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerOwnerQrCodeDTO cloudTalkSDKServerOwnerQrCodeDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerOwnerQrCodeDTO.class, request);
            String appId = cloudTalkSDKServerOwnerQrCodeDTO.getAppId();
            //LOG.info("====云对讲SDK设置业主二维码入参：appid:" + appId + " projectId:" + cloudTalkSDKServerOwnerQrCodeDTO.getProjectId() + " userId:" + cloudTalkSDKServerOwnerQrCodeDTO.getUserId());
            String projectId = cloudTalkSDKServerOwnerQrCodeDTO.getProjectId();
            // 解密项目id
//            projectId = DesEncryptUtil.projectIdDesEncrypt(projectId) == null ? projectId : DesEncryptUtil.projectIdDesEncrypt(projectId);
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            if (projectIdList == null || projectIdList.isEmpty() || !projectIdList.contains(projectId)) {
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode());
            }

            // 更新用户二维码
            iAppDeviceServiceClient.setUserQrCode(cloudTalkSDKServerOwnerQrCodeDTO.getUserId(),projectId,null);
            AppGetQrcodeVO userQrcode = iAppMineServiceClient.getUserQrcode(projectId, cloudTalkSDKServerOwnerQrCodeDTO.getUserId(),null);
            Map<String,String> map = new HashMap<>();
            map.put("qrcodeStr",userQrcode.getQrcode());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "设置业主二维码");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK_服务端_用户服务】设置业主二维码失败",e);
        }
    }

    /**
     * <desc>
     *      设置开门密码
     * </desc>
     *
     * @return
     * @author Juguang.S
     * @createDate 2018/11/21
     */
    @RequestMapping(path = "/server/setOpenPwd",method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SET_OPEN_PWD_LOG_DESC)
    @ResponseBody
    public Object setDoorPwd(){
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerOpenPwdDTO openPwdDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerOpenPwdDTO.class, request);
            String userId = openPwdDTO.getUserId();
            String openPwd = openPwdDTO.getOpenPwd();
            String projectId = openPwdDTO.getProjectId();
            String appId = openPwdDTO.getAppId();
            //LOG.info("====云对讲SDK设置开门密码入参：appid:" + appId + " projectId:" + projectId + " userId:" + userId + " openPwd:" + openPwd);
            // 解密项目id
            //projectId = DesEncryptUtil.projectIdDesEncrypt(projectId) == null ? projectId : DesEncryptUtil.projectIdDesEncrypt(projectId);
            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            String projectStr = null;
            if(!projectIdList.isEmpty() && projectIdList!=null){
                projectStr = String.join(",",projectIdList);
            }
            if(!projectStr.contains(projectId)){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode());
            }

            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(openPwd) || StringUtils.isBlank(userId)){
                return new MessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode());
            }else if(!openPwd.matches("[0-9]{4}")){
                ErrorCode errorCode =AppErrorCodeEnum.OPEN_PASSWORD_IS_ERROR.getErrorCode();
                return new MessageVO(errorCode);
            }

            //检查用户是否是业主
            if(iAppRegisterServiceClient.countUserAttacheInfoInProject(userId,projectId) < 1){
                ErrorCode errorCode = AppErrorCodeEnum.USER_NOT_OWNER.getErrorCode();
                return new MessageVO(errorCode);
            }
            iAppRoomServiceClient.setOpenPwd(projectId,userId,openPwd);
            //推送设备拉取业主信息
            iAppDeviceServiceClient.pushCloudDeviceAuth(projectId,userId,
                    SmartCommunityEnum.PUSH_ROOM.getCommandType());
            ErrorCode errorCode =BaseErrorCodeEnum.SUCCESS.getErrorCode();
            messageVO=new MessageVO(errorCode);
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",LogDescConstant.SDK_SERVER_SET_OPEN_PWD_LOG_DESC);
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK_server_setDoorPwd】设置开门密码失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      设置访客动态密码
     * </desc>
     *
     * @return
     * @author Juguang.S
     * @createDate 2018/11/24
     */
    @PostMapping(path = "/server/getVisitorQrCode")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_SET_VISITOR_DYPWD_LOG_DESC)
    @ResponseBody
    public Object getVisitorQrCode(){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            CloudTalkSDKServerVisitorPwdDTO visitorPwdDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudTalkSDKServerVisitorPwdDTO.class, request);
            String appId = visitorPwdDTO.getAppId();
            String projectId = visitorPwdDTO.getProjectId();
            String userId = visitorPwdDTO.getUserId();
            String buildNum = visitorPwdDTO.getBuildNum();
            String unitNum = visitorPwdDTO.getUnitNum();
            String visitorName = visitorPwdDTO.getVisitorName();
            String visitorPhone = visitorPwdDTO.getVisitorPhone();
            String floorNum = visitorPwdDTO.getFloorNum();
            String effectiveTime = visitorPwdDTO.getEffectiveTime();
            String viladType = visitorPwdDTO.getViladType();

            if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(userId)
                    || StringUtils.isEmpty(buildNum) || StringUtils.isEmpty(unitNum) || StringUtils.isEmpty(visitorName)
                    || StringUtils.isEmpty(visitorPhone) || StringUtils.isEmpty(floorNum) || StringUtils.isEmpty(effectiveTime) || StringUtils.isEmpty(viladType)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if(Integer.parseInt(effectiveTime)>1440){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_SDK_DYPWD_ERR.getErrorCode());
            }
            //LOG.info("云对讲SDK设置访客动态密码入参：appid:" + appId + " projectId:" + projectId + " userId:" + userId);
            // 解密项目id
            //projectId = DesEncryptUtil.projectIdDesEncrypt(projectId) == null ? projectId : DesEncryptUtil.projectIdDesEncrypt(projectId);

            //校验buildNum unitNum 该项目下是否有该单元信息
            visitorPwdDTO.setProjectId(projectId);
            if(iCloudTalkSDKServerUserServiceClient.getExistBuildInfo(visitorPwdDTO)==null){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_NOT_EXIST_BUILDNUM_ERR.getErrorCode());
            }

            //根据ProjectId,buildNum查询出该楼栋的最高楼层
            if(iCloudTalkSDKServerUserServiceClient.getBuildFloorNum(projectId,buildNum)<Integer.parseInt(floorNum)){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_SDK_FLOORNUM_ERR.getErrorCode());
            }

            // 校验开发者账号是否有该项目的权限
            List<String> projectIdList = iCloudTalkSDKServerUserServiceClient.getProjectIdByParams(appId);
            String projectStr = null;
            if(!projectIdList.isEmpty() && projectIdList!=null){
                projectStr = String.join(",",projectIdList);
            }
            if(!projectStr.contains(projectId)){
                return new MessageVO(CloudTalkErrorCodeEnum.SERVER_CHECKDEVELOPER_AUTH.getErrorCode());
            }
            AppVisitorPassCodeRecordPO passPO = iCloudTalkSDKServerUserServiceClient.getVisitorPwdAndQrCode(visitorPwdDTO);
            Map<String,String> returnMap =  new HashMap<>();
            returnMap.put("password",passPO.getPassword());
            returnMap.put("qrcodeStr",passPO.getQrcode());
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",LogDescConstant.SDK_SERVER_SET_VISITOR_DYPWD_LOG_DESC);
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_TALK_TYPE_LOG_DESC);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),returnMap);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK_server_getVisitorQrCode】设置访客动态密码失败",e);
        }
    }

}